import json
# 将硬盘中的文件加载到内存中
# file = open('a.text', 'w', encoding="utf-8")
#
# file.write('hello world')
#
# file.close()
#
# with open('a.text', encoding="utf-8") as f:
#     buf = f.read()
#     print(buf)

# 按行读取文件readline
# with open('a.text',encoding='utf-8') as f:
#     while True:
#         buf = f.readline()
#         if buf == "":
#             break
#         else:
#             print(buf)

# json文件相关知识
# 读取json文件
# 麻烦
# with open('info.json',encoding='utf-8') as f:
#     buf = f.read()
#     print(buf)
# 常用,专门的方法
# with open('info.json',encoding='utf-8') as f:
#     buf = json.load(f)
#     print(buf)
#     # 姓名
#     print(buf.get('name'))
#     # 爱好
#     print(buf.get('hoppy')[1])
# 两个对象
with open('info.json',encoding='utf-8') as f:
    buf_list = json.load(f)
    for buf in buf_list:
        sex = "男" if buf.get('isMan') else "女"
        # if buf.get('isMan'):
        #     sex = "男"
        # else:
        #     sex = "女"
        print(f"姓名{buf.get('name')} 年龄:{buf.get('age')} "
              f"性别：{sex} 城市：{buf.get('address').get('city')}")

# json文件的保存
info = {"name":"小绿","age":20}
with open('info2.json','w',encoding='utf-8') as f:
    # 把什么文件写到那个json文件中,indent缩进
    json.dump(info,f,ensure_ascii=False,indent=2)


